using System;
using System.Data;
using System.IO;
using System.Web;
using System.Web.UI.WebControls;
using Framework.Library;
using Framework.Library.Utilities;
using Framework.Module.Adsvertising.Lib.Data;
using Framework.Module.Adsvertising.Lib.Distributor;

namespace Framework.Module.Adsvertising.Advertise
{
	public class Advertisement : Table
	{	
		private string _position = string.Empty;
		public string Position
		{
			get { return _position;}
			set {_position = value;}
		}		
		private HorizontalAlign _align;
		public HorizontalAlign Align
		{
			get { return _align;}
			set { _align = value;}
		}
		private string _param = "";
		public string Param
		{
			get { return _param;}
			set { _param = value;}
		}

        private string _divLeft = "";
        public string DivAdsLeft
        {
            get { return _divLeft; }
            set { _divLeft = value; }
        }

        private string _divRight = "";
        public string DivAdsRight
        {
            get { return _divRight; }
            set { _divRight = value; }
        }

		private PositionInfo posInfo;	
		private TableCell GetNewCell(DataRow curData)
		{
			TableCell retVal = new TableCell();
			retVal.HorizontalAlign = Align;
			int width = Convert.ToInt32(curData["Advertise_Width"]);
			int height = Convert.ToInt32(curData["Advertise_Height"]);
			string path = curData["Advertise_Path"].ToString();
			switch (curData["Advertise_Type"].ToString())
			{
				case "image":
					Image img = new Image();
					img.ImageUrl = path;
					if (width != 0) img.Width = width;
					if (height != 0) img.Height = height;
					img.Attributes.Add("style","cursor:hand");
					if(ConvertUtility.ToString(curData["Advertise_Target"]) == "_blank")
                        img.Attributes.Add("onclick", "javascript:window.open('/Modules/Adsvertising/ClickCounter.aspx?id=" + curData["Advertise_ID"].ToString() + "');");
					else if(ConvertUtility.ToString(curData["Advertise_Target"]) == "")
                        img.Attributes.Add("onclick", "javascript:window.open('/Modules/Adsvertising/ClickCounter.aspx?id=" + curData["Advertise_ID"].ToString() + "','_self');");
					retVal.Controls.Add(img);							
					break;
				case "flash":
                    Literal flash = new Literal();
                    string strFileName = Path.GetFileNameWithoutExtension(path);
                    strFileName = path.Substring(0,path.LastIndexOf("/")+1) + strFileName;
                    flash.Text = MultimediaUtility.strInitFlashWithActiveContent(strFileName, width, height,"center");
                    retVal.Controls.Add(flash);
                    break;
				case "media":
					Literal media = new Literal();
					media.Text = MultimediaUtility.strInitMultimedia(path,width,height);
					retVal.Controls.Add(media);
					break;
			}	
			return retVal;
		}
		public static string strInitRotate(int posID) 
		{			
			string retVal = 
				"<script language=\"JavaScript\">\n" +
				"var curBanner" + posID + ";\n" +
				"var BannerLnk" + posID + ";\n" +
				"function ChangeBanner" + posID + "(arBanner, strLnk, strImg)\n" +
				"{\n" +
				"	if (arBanner.length==0)\n" +
				"		return;\n" +
				"	curBanner" + posID +  "++;\n" +
				"	if (curBanner" + posID +  " >= arBanner.length)\n" +
				"	{\n" +
				"		curBanner" + posID +  "=0;\n" +
				"	}\n" +
				"	document.links[BannerLnk" + posID + "].href= arBanner[curBanner" + posID +  "][1];\n" +
				"	document.images[strImg].src = arBanner[curBanner" + posID +  "][0];\n" +
				"	document.images[strImg].width = arBanner[curBanner" + posID +  "][2];\n" +
				"	document.images[strImg].height = arBanner[curBanner" + posID +  "][3];\n" +
				"}\n" +
				"function DisplayBanner" + posID + "(strAr, arBanner, strLnk, strImg,strClickTarget)\n" +
				"{\n" +
				"	curBanner" + posID +  "=Math.floor(Math.random()*12321) % arBanner.length;\n" +
				"	BannerLnk" + posID + "=document.links.length;\n" +
				"	document.write('<a name=\"',strLnk,'\" href=\"', arBanner[curBanner" + posID +  "][1], '\" target=\"',strClickTarget,'\"><img name=\"',strImg,'\" src=\"', arBanner[curBanner" + posID +  "][0], '\" width=', arBanner[curBanner" + posID +  "][2], ' height=',arBanner[curBanner" + posID +  "][3], ' border=0></a>');\n" +
				"	setInterval('ChangeBanner" + posID + "('+strAr+', \\''+strLnk+'\\', \\''+strImg+'\\')', 7000);\n" +
				"}\n" + 
				"</script>";
			return retVal;			
		}	
		protected override void OnPreRender(EventArgs e)
		{			
			int paramValue = 0;
			if (HttpContext.Current.Request.QueryString[Param] != null) paramValue = ConvertUtility.ToInt32(HttpContext.Current.Request.QueryString[Param]);
			posInfo = PositionDistributor.GetInfoByPosition(_position);
			if (posInfo == null)
			{
				this.Visible = false;
				return;
			}	
			this.Rows.Clear();	
			this.CellPadding = 0; this.CellSpacing = 0; this.BorderWidth = 0;
			DataTable source = AdvertiseDistributor.GetAvailables(posInfo.Pos_ID, paramValue);
			if (source.Rows.Count == 0) return;
			if (posInfo.Pos_Type == "default")
			{				
				foreach( DataRow row in source.Rows)
				{															
					TableRow newRow = new TableRow(); 
                    newRow.Cells.Add(GetNewCell(row)); 
                    this.Rows.Add(newRow);

                    if (posInfo.Pos_SeparateCode != "" && posInfo.Pos_SeparateCode != null)
                    {
                        newRow = new TableRow();
                        newRow.Cells.Add(new TableCell());
                        newRow.Cells[0].Text = posInfo.Pos_SeparateCode;
                        this.Rows.Add(newRow);
                    }
				}																	 
			}			
			if (posInfo.Pos_Type == "rotator")
			{				
				string retVal = strInitRotate(posInfo.Pos_ID);				
				retVal += "<script language=\"JavaScript\">\n";
				retVal += "var arZone = new Array(\n";
				for(int i = 0 ;i < source.Rows.Count ; i++)
				{										
					DataRow curData = source.Rows[i];
					int width = Convert.ToInt32(curData["Advertise_Width"]);
					int height = Convert.ToInt32(curData["Advertise_Height"]);
					
					retVal += "new Array('" + curData["Advertise_Path"].ToString() + "', '/Modules/Advertise/ClickCounter.aspx?id=" + curData["Advertise_ID"].ToString() + "'," + width + "," + height + ")";
					
					if (i != (source.Rows.Count - 1) ) retVal += ",\n";							
					else retVal += "\n";									
				}				
				retVal += ");\n";
				retVal += "DisplayBanner" + posInfo.Pos_ID + "('arZone', arZone, 'lnkRotateBanner', 'imgRotateBanner','" + "_blank" + "');\n";
				retVal += "</script>";
				
				TableRow rowRotator = new TableRow(); 
                rowRotator.Cells.Add( new TableCell()); 
                rowRotator.Cells[0].Text = retVal; 
                this.Rows.Add(rowRotator);
			}
			if (posInfo.Pos_Type == "popup")
			{
				string retVal = 
				"<script> \n" +
				"	function PopUpShow" + posInfo.Pos_ID + "( source, width, height )\n" +
				"	{\n" +
				"		window.open( source , 'PopUpShow" + posInfo.Pos_ID + "', 'resizable=no,width=' + width  + ', height=' + height + ',top=0,bottom=0,right=0,left=0,statusbar=no,menubar=no,toolbar=no,scrollbars=no');\n" +
				"	}\n";
				foreach( DataRow row in source.Rows)
				{
					retVal += "	PopUpShow" + posInfo.Pos_ID + "('" + row["Advertise_Path"].ToString() + "'," + row["Advertise_Width"].ToString() + "," + row["Advertise_Height"].ToString() + ");\n";
					break;
				}
				
				retVal += "</script>";

				TableRow newRow = new TableRow(); 
                newRow.Cells.Add(new TableCell()); 
                newRow.Cells[0].Text = retVal;
				this.Rows.Add(newRow);
			}
			if (posInfo.Pos_Type == "random")
			{
				string retVal = "<script language=\"JavaScript\">\n";
				string arrImages = "var arrImages" + posInfo.Pos_ID + " = new Array(\n";
				string arrIndex = "var arrIndex" + posInfo.Pos_ID + " = new Array(\n";
				for (int i = 0; i < source.Rows.Count; i++)
				{
					DataRow curData = source.Rows[i];
					int width = Convert.ToInt32(curData["Advertise_Width"]);
					int height = Convert.ToInt32(curData["Advertise_Height"]);
					string id = curData["Advertise_ID"].ToString();
					arrImages += " new Array('" + curData["Advertise_Path"].ToString() + "','" + width + "','" + height + "','" + id + "')";
					arrIndex += i.ToString();
					if (i != (source.Rows.Count - 1))
					{
						arrImages += ",\n";
						arrIndex += ",";
					}
					else
					{
						arrImages += "\n";
						arrIndex += "";
					}
				}
				retVal += arrImages + ");\n" + arrIndex + ");\n" ;
				
				retVal += "function RandomImg" + posInfo.Pos_ID + "()\n" +
					"{\n" +
					"	for ( i= 0; i < " + source.Rows.Count + "; i ++)\n" +
					"	{\n" +
					"		j = Math.round(Math.random() *" + Convert.ToString(source.Rows.Count-1) + "); \n" +
					"		if (j !=i)\n" +
					"		{\n" +
					"			temp = arrIndex" + posInfo.Pos_ID + "[i]; \n" +
					"			arrIndex" + posInfo.Pos_ID + "[i] = arrIndex" + posInfo.Pos_ID + "[j]; \n" +
					"			arrIndex" + posInfo.Pos_ID +  "[j] = temp; \n" +
					"		}\n" +
					"	}\n" +
					"}\n";
				string itemImg = "arrImages" + posInfo.Pos_ID + "[arrIndex" + posInfo.Pos_ID + "[i]" +  "]";
				string image = "<img  border=0 src='\" + " + itemImg + "[0] + \"' width='\" + " + itemImg + "[1]+ \"' height='\" + " + itemImg + "[2]+ \"'>";
				retVal += "function Display" + posInfo.Pos_ID + "()\n" +
					"{\n" +
					"	RandomImg" + posInfo.Pos_ID + "();\r"  +
					"	for (i= 0; i < " + source.Rows.Count + "; i ++)\n" +
					"	{\n" +
					"		document.write(\"<a target='_blank' href='/Modules/Advertise/ClickCounter.aspx?id=\" + "  + itemImg + "[3] + \"'>" + image + "</a>\"); \n" +
					"		document.write(\"" + posInfo.Pos_SeparateCode + "\"); \n" +
					"	}\n" +
					"}\n" +
					" Display" + posInfo.Pos_ID + "();\n</script>";
				this.Rows.Add(new TableRow()); 
                this.Rows[0].Cells.Add(new TableCell()); 
                this.Rows[0].Cells[0].Text = retVal; 
                this.Rows[0].Cells[0].HorizontalAlign = Align;
			}
            if (posInfo.Pos_Type == "leftfloat")
            {
                foreach (DataRow row in source.Rows)
                {
                    TableRow newRow = new TableRow();
                    newRow.Cells.Add(GetNewCell(row));
                    this.Rows.Add(newRow);

                    if (posInfo.Pos_SeparateCode != "" && posInfo.Pos_SeparateCode != null)
                    {
                        newRow = new TableRow();
                        newRow.Cells.Add(new TableCell());
                        newRow.Cells[0].Text = posInfo.Pos_SeparateCode;
                        this.Rows.Add(newRow);
                    }
                }		

                string retVal = "";
                retVal += "<script language=\"JavaScript\">\n";
                retVal += "function FloatTopDivLeft() \n" +
                            "{\n" +
                                "startXLeft = document.body.clientWidth - document.body.clientWidth, startYLeft = 71; \n" +
                                "var ns = (navigator.appName.indexOf(\"Netscape\") != -1); \n" +
                                "var d = document; \n" +
                                "if (document.body.clientWidth < 980) startXLeft = - document.body.clientWidth; \n" +
                                "function mlleft(id) \n" +
                                "{ \n" +
                                    "var objAdDivLeft = document.getElementById(\"" + DivAdsLeft + "\");  \n" +
                                    "if(!objAdDivLeft) return; \n" +
                                    "var el=d.getElementById?d.getElementById(id):d.all?d.all[id]:d.layers[id]; \n" +
                                    "if(d.layers)el.style=el; \n" +
                                    "el.sP=function(x,y){this.style.left=x;this.style.top=y;}; \n" +
                                    "el.x = startXLeft; \n" +
                                    "el.y = startYLeft; \n" +
                                    "return el; \n" +
                                "} \n" +

                                "window.stayTopLeft=function() \n" +
                                "{ \n" +
                                    "if (document.documentElement && document.documentElement.scrollTop) \n" +
                                        "var pY = ns ? pageYOffset : document.documentElement.scrollTop; \n" +
                                    "else if (document.body) \n" +
                                        "var pY = ns ? pageYOffset : document.body.scrollTop; \n" +

                                    "if (document.body.scrollTop > 71){startYLeft = 3} else {startYLeft = 71}; \n" +
                                    "ftlObjLeft.y += (pY + startYLeft - ftlObjLeft.y)/8; \n" +
                                    "ftlObjLeft.sP(ftlObjLeft.x, ftlObjLeft.y); \n" +
                                    "var objAdDivLeft = document.getElementById(\"" + DivAdsLeft + "\"); \n" +

                                    "setTimeout(\"stayTopLeft()\", 1); \n" +

                                "} \n" +
                                "ftlObjLeft = mlleft(\"" + DivAdsLeft + "\"); \n" +
                                "stayTopLeft(); \n" +
                            "} \n" +

                            "function ShowAdDivLeft() \n" +
                            "{ \n" +
                                "var objAdDivLeft  = document.getElementById(\"" + DivAdsLeft + "\"); \n" +
                                "if (document.body.clientWidth < 980) \n" +
                                "{ \n" +
                                    "if(objAdDivLeft)  objAdDivLeft.style.left  = -110; \n" +
                                "} \n" +
                                "else \n" +
                                "{ \n" +
                                    "if(objAdDivLeft) objAdDivLeft.style.left  = 0; \n" +
                                "} \n" +
                                "FloatTopDivLeft(); \n" +
                            "}\n" +
                            "ShowAdDivLeft(); \n" +
                            "LComplete = 1; \n";			              
                retVal += "</script>";

                TableRow _newRow = new TableRow();
                _newRow.Cells.Add(new TableCell());
                _newRow.Cells[0].Text = retVal;
                this.Rows.Add(_newRow);
            }
            if (posInfo.Pos_Type == "rightfloat")
            {
                foreach (DataRow row in source.Rows)
                {
                    TableRow newRow = new TableRow();
                    newRow.Cells.Add(GetNewCell(row));
                    this.Rows.Add(newRow);

                    if (posInfo.Pos_SeparateCode != "" && posInfo.Pos_SeparateCode != null)
                    {
                        newRow = new TableRow();
                        newRow.Cells.Add(new TableCell());
                        newRow.Cells[0].Text = posInfo.Pos_SeparateCode;
                        this.Rows.Add(newRow);
                    }
                }		

                string retVal = "";
                retVal += "<script language=\"JavaScript\">\n";
                retVal += "function FloatTopDiv() \n" +
                             "{ \n" +
                                 "startX = document.body.clientWidth - 110, startY = 71; \n" +
                                 "var ns = (navigator.appName.indexOf(\"Netscape\") != -1); \n" +
                                 "var d = document; \n" +

                                 "if (document.body.clientWidth < 980) startX = -110; \n" +

                                 "function ml(id) \n" +
                                 "{ \n" +
                                     "var objAdDivRight = document.getElementById(\"" + DivAdsRight + "\"); \n" +
                                     "if(!objAdDivRight) return; \n" +
                                     "var el=d.getElementById?d.getElementById(id):d.all?d.all[id]:d.layers[id]; \n" +
                                     "if(d.layers)el.style=el; \n" +
                                     "el.sP=function(x,y){this.style.left=x;this.style.top=y;}; \n" +
                                     "el.x = startX; \n" +
                                     "el.y = startY; \n" +
                                     "return el; \n" +
                                 "} \n" +

                                 "window.stayTopRight=function() \n" +
                                 "{ \n" +
                                     "if (document.documentElement && document.documentElement.scrollTop) \n" +
                                         "var pY = ns ? pageYOffset : document.documentElement.scrollTop; \n" +
                                     "else if (document.body) \n" +
                                         "var pY = ns ? pageYOffset : document.body.scrollTop; \n" +

                                     "if (document.body.scrollTop > 71){startY = 3} else {startY = 71}; \n" +
                                     "ftlObj.y += (pY + startY - ftlObj.y)/8; \n" +
                                     "ftlObj.sP(ftlObj.x, ftlObj.y); \n" +
                                     "var objAdDivRight = document.getElementById(\"" + DivAdsRight + "\");	 \n" +

                                     "setTimeout(\"stayTopRight()\", 1); \n" +

                                 "} \n" +
                                 "ftlObj = ml(\"" + DivAdsRight + "\"); \n" +
                                 "stayTopRight(); \n" +
                             "} \n" +

                             "function ShowAdDiv() \n" +
                             "{ \n" +
                                 "var objAdDivRight = document.getElementById(\"" + DivAdsRight + "\"); \n" +
                                 "if (document.body.clientWidth < 980) \n" +
                                 "{ \n" +
                                     "if(objAdDivRight) objAdDivRight.style.left = -110; \n" +
                                 "} \n" +
                                 "else \n" +
                                 "{ \n" +
                                     "if(objAdDivRight) objAdDivRight.style.left = document.body.clientWidth - 110; \n" +
                                 "} \n" +
                                 "FloatTopDiv(); \n" +
                             "} \n" +
                             "ShowAdDiv(); \n" +
                             "LComplete = 1; \n";                      
               
                retVal += "</script>";

                TableRow _newRow = new TableRow();
                _newRow.Cells.Add(new TableCell());
                _newRow.Cells[0].Text = retVal;
                this.Rows.Add(_newRow);
            }
		}	
	}
}
